using System.Reflection;
using SuperSocket.Command;

namespace Example.Command.Kernel  ;
public class TraceFilter : CommandFilterAttribute 
{
    
    //在命令执行前被调用
    public override bool OnCommandExecuting (CommandExecutingContext ctx) {
        var cmd = ctx.CurrentCommand.GetType().GetCustomAttribute<CommandAttribute>()?.Name;
        Console.WriteLine($"=> [Trace] {cmd} 将被执行...");
        
        ctx.Session["Cost"] = DateTime.Now.Ticks; //设置上下文透传参数,模拟Command耗时
        return true;
    }

    //在命令执行后被调用
    public override void OnCommandExecuted (CommandExecutingContext ctx) {
        var cost = (DateTime.Now.Ticks- long.Parse(ctx.Session["Cost"].ToString()!));
        var costSeconds = (double)cost / 10000000;
        var keeps = (ctx.Session.LastActiveTime - ctx.Session.StartTime).TotalSeconds;
        Console.WriteLine($"=> [Trace] 客户端[{ctx.Session.RemoteEndPoint}]的会话({ctx.Session.SessionID})已持续 {keeps} 秒,本次耗时 {costSeconds} 秒.");
        
        var cmd = ctx.CurrentCommand.GetType().GetCustomAttribute<CommandAttribute>()?.Name;
        Console.WriteLine($"=> [Trace] {cmd} 执行结束...");
        Console.WriteLine();
    }
}